/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tcloudclient.fileSystem;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import tcloudclient.Utils;
import tcloudclient.actionManager.ActionExecuteEventInterface;
import tcloudclient.actionManager.ActionTypeClientEnum;

/**
 *
 * @author Tomas
 */
public class FileSystemActionListener implements ActionExecuteEventInterface {

    private FileNode rootFile;

    public FileSystemActionListener(FileNode rootFile) {
        this.rootFile = rootFile;
    }

    @Override
    public boolean canExecuteAction(String[] path, long fileVersion, ActionTypeClientEnum actionType) {
        FileNode fileNode;
        if (actionType != ActionTypeClientEnum.NEW) {
            fileNode = FileSystemUtils.findFileNode(path, rootFile);
            if (fileNode.getName().equalsIgnoreCase(path[path.length - 1])) {
                if (fileNode.getStatus() != FileStatusEnum.NOMODIFY) {
                    //TODO fire conflict event, wait for response
                    //file is localy modifyted
                    return false;
                }
            }
        } else {
            fileNode = FileSystemUtils.findParentNode(path, rootFile);
            for (FileNode fileChilds : fileNode.getChilds()) {
                if (fileChilds.getName().equalsIgnoreCase(path[path.length - 1])) {
                    //TODO fire conflict event, wait for response
                    //file is already exist
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public void actionExecuted(String[] path, long fileVersion, ActionTypeClientEnum actionTypeEnum) {
        FileNode fileNode;
        if (actionTypeEnum == ActionTypeClientEnum.UPDATE) {
            fileNode = FileSystemUtils.findFileNode(path, rootFile);            
            fileNode.setLastChange(fileNode.getFile().lastModified());
            fileNode.setStatus(FileStatusEnum.NOMODIFY);
            fileNode.setVersion((int)fileVersion);
        } else if (actionTypeEnum == ActionTypeClientEnum.NEW){
            fileNode = FileSystemUtils.findParentNode(path, rootFile);
            File file = new File(Utils.generatePaht(path));
            FileNode newFileNode = new FileNode(file, FileStatusEnum.NOMODIFY, new Date(file.lastModified()), new ArrayList<FileNode>());            
            newFileNode.setVersion((int)fileVersion);
            fileNode.getChilds().add(newFileNode);
        }else{
            FileSystemUtils.findParentNode(path, rootFile).getChilds().remove(FileSystemUtils.findFileNode(path, rootFile));
        }
    }
}
